package com.ebuilder.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import com.ebuilder.beans.Person;
import com.ebuilder.util.DBUtil;

public class PersonDao {
	
	public Person getPerson(String userId) {
		Session session = DBUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		Person p = null;
		
		List result = session.find("from Person as p");
		Iterator it = result.iterator();
		while (it.hasNext()) {
			Person person = (Person)it.next();
			if(userId.equals(person.getUserId())) {
				p = person;
			}
		}
		
		session.close();
		return p;
	}
	
	public void createPerson(Person p) {
		Session session = DBUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(p);
	
		session.getTransaction().commit();
	}
	
	public void updatePerson(Person p, String userId) {
		Session session = DBUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Person person = getPerson(userId);
		person.setUserId(p.getUserId());
		person.setAddress(p.getAddress());
		person.setEmail(p.getEmail());
		person.setPassword(p.getPassword());
		session.getTransaction().commit();
		session.close();
	}
	
	public void deletePerson(String userId) {
		Session session = DBUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Person p = (Person)session.load(Person.class, userId);
		session.delete(p);
		session.getTransaction().commit();
		session.close();
	}
	
	public boolean personExist(String userId) {
		Session session = DBUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		Person p = getPerson(userId);
		session.close();
		if(p != null) {
			return true;
		}
		return false;
	}
}
